<template>
  <div class="call-wrapper">
    <TUICallKit v-show="initialized" @hangup="onHangup" @cancel="onCancel" />
    <div v-show="!initialized" class="initialization-container">
      <div v-if="loading" class="loading-message">
        <div class="spinner"></div>
        <p>{{ loadingMessage }}</p>
      </div>
      <div v-else class="error-message">
        <p>{{ errorMessage }}</p>
        <button @click="retryInit" class="retry-button">重试</button>
      </div>
    </div>
  </div>
</template>

<script>
// https://cloud.tencent.com/document/product/647/78731
import {
  TUICallKit,
  TUICallKitServer,
  TUICallType,
} from "@tencentcloud/call-uikit-vue";

export default {
  name: "TUICall",
  components: {
    TUICallKit,
  },
  data() {
    return {
      initialized: false,
      loading: false,
      loadingMessage: "",
      errorMessage: "",
    };
  },
  mounted() {
    /***
     * 登录初始化
     */
    this.loading = true;
    this.loadingMessage = "音视频通话初始化中，请稍候...";
    setTimeout(() => {
      this.initCallkit();
    }, 3000);
  },
  methods: {
    async call(calledUserId) {
      // 等待组件渲染完成
      await this.$nextTick();

      // 延时发起呼叫，确保组件已正确挂载
      return new Promise((resolve) => {
        setTimeout(async () => {
          try {
            console.log("延时发起呼叫======calls");
            console.log("被叫用户ID:", calledUserId);

            await TUICallKitServer.calls({
              userIDList: [calledUserId],
              type: TUICallType.VIDEO_CALL,
            });

            resolve();
          } catch (callError) {
            console.error("发起通话失败:", callError);
            console.error("发起通话失败calledUserId:", calledUserId);

            if (
              callError.name === "NotAllowedError" ||
              callError.message?.includes("NotAllowedError")
            ) {
              this.errorMessage =
                "摄像头/麦克风访问被拒绝，请检查浏览器权限设置并重试";
            } else {
              this.errorMessage =
                "发起通话失败: " + (callError.message || "未知错误");
            }
            this.initialized = false;
            resolve();
          }
        }, 1000);
      });
    },

    async initCallkit() {
      try {
        // 从URL参数中获取会议信息
        const urlParams = new URLSearchParams(window.location.search);
        const meetingInfo = urlParams.get("httpsMettingInfo");

        if (!meetingInfo) {
          throw new Error("未找到会议信息");
        }

        let meetingInfoData;
        try {
          meetingInfoData = JSON.parse(decodeURIComponent(meetingInfo));
        } catch (e) {
          throw new Error("解析会议信息失败");
        }

        const SDKAppID = parseInt(meetingInfoData.SDKAppID);
        const userSig = meetingInfoData.userSig;
        const userID = String(meetingInfoData.userID); // 确保是字符串类型
        const calledUserId = meetingInfoData.calledUserId || "user-null";

        console.log("音视频通话初始化参数", { SDKAppID, userSig, userID });

        if (!SDKAppID || !userSig || !userID) {
          throw new Error("缺少必要的参数: SDKAppID, userSig 或 userID");
        }

        // 检查 TUICallKitServer 是否已定义
        if (!TUICallKitServer) {
          throw new Error("TUICallKitServer 未正确加载，请检查网络连接后重试");
        }

        console.log("音视频通话初始化成功======init", TUICallKitServer);

        // 初始化 TUICallKitServer
        await TUICallKitServer.init({
          SDKAppID,
          userID,
          userSig,
        });

        // 设置初始化成功标志
        this.initialized = true;

        // 发起呼叫
        await this.call(calledUserId);
      } catch (error) {
        console.log("[TUICallKit] 音视频通话初始化失败 error.", error);

        if (error.message?.includes("TUICallEngineWASM")) {
          this.errorMessage = "通话引擎加载失败，请检查网络连接后重试";
        } else if (
          error.name === "NotAllowedError" ||
          error.message?.includes("NotAllowedError")
        ) {
          this.errorMessage =
            "摄像头/麦克风访问被拒绝，请检查浏览器权限设置并重试";
        } else {
          this.errorMessage = "初始化失败: " + (error.message || "未知错误");
        }
        this.initialized = false;
      } finally {
        this.loading = false;
      }
    },

    retryInit() {
      this.errorMessage = "";
      this.initialized = false;
      this.initCallkit();
    },

    onHangup() {
      logger.info("onHangup");

      // 当用户挂断通话时，向父级发送消息
      window.parent.postMessage({ type: "hangup", message: "通话已挂断" }, "*");
    },

    onCancel() {
      logger.info("onCancel");
      // 当用户取消通话时，向父级发送消息
      window.parent.postMessage({ type: "cancel", message: "通话已取消" }, "*");
    },
  },
};
</script>

<style scoped>
.call-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  width: 100%;
  height: 100%;
}

.initialization-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f8f9fa;
}

.loading-message,
.error-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: white;
  text-align: center;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-message p,
.error-message p {
  color: #333;
  margin-bottom: 20px;
  font-size: 16px;
}

.error-message p {
  color: #dc3545;
}

.retry-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.retry-button:hover {
  background-color: #0056b3;
}

.retry-button:active {
  transform: translateY(1px);
}
</style>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
</style>
